﻿/* ######################################## *\
 * ### Copyright (C) 2009 AJ Ravindiran ### *
\* ######################################## */
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using AJRavindiran.Jolt.Storage;

namespace AJRavindiran.Jolt.RuneScape.Database.Configs
{
    /// <summary>
    /// Represents a configuration reader.
    /// </summary>
    public class ConfigLoader
    {
        /// <summary>
        /// Load configurations from a given database.
        /// </summary>
        /// <param name="databaseTable">The database to collection configurations from.</param>
        /// <param name="configurations">The dictionary to store configurations in.</param>
        public static void Load(string databaseTable, Dictionary<string, dynamic> configurations)
        {
            DataTable dataTable = null;
            using (DatabaseClient dbClient = Jolt.GetDatabase().GetClient())
            {
                dataTable = dbClient.ReadDataTable("SELECT * FROM " + databaseTable + "");
            }

            try
            {
                // We now determine what type of variable the value is, and convert them.
                foreach (DataRow row in dataTable.Rows)
                {
                    if (row[1].Equals("boolean"))
                        configurations.Add(row[0].ToString(), Convert.ToBoolean(row[2]));
                    else if (row[1].Equals("byte"))
                        configurations.Add(row[0].ToString(), Convert.ToByte(row[2]));
                    else if (row[1].Equals("int16"))
                        configurations.Add(row[0].ToString(), Convert.ToInt16(row[2]));
                    else if (row[1].Equals("int32"))
                        configurations.Add(row[0].ToString(), Convert.ToInt32(row[2]));
                    else if (row[1].Equals("int64"))
                        configurations.Add(row[0].ToString(), Convert.ToInt64(row[2]));
                    else
                        configurations.Add(row[0].ToString(), row[2]);
                }
            }
            catch (Exception ex)
            {
                Jolt.GetLog().WriteException(ex);
            }
        }
    }
}
